const express = require('express');
const fs = require('fs');
const app = express();
const PORT = 3000;

app.use(express.json());
const cors = require('cors');
app.use(cors({
  origin: 'http://localhost:8080', // 允许来自前端开发服务器的请求
  methods: ['GET', 'POST'], // 允许的方法
}));

// 获取用户列表
app.get('/api/users', (req, res) => {
  fs.readFile('users.json', (err, data) => {
    if (err) {
      return res.status(500).json({ message: 'Error reading users.json' });
    }
    const usersData = JSON.parse(data);
    res.json(usersData.userslist); // 确保返回 userslist 数组
  });
});

// 注册新用户
app.post('/api/register', (req, res) => {
  const { name, password } = req.body;
  fs.readFile('users.json', (err, data) => {
    if (err) {
      return res.status(500).json({ message: 'Error reading users.json' });
    }
    const usersData = JSON.parse(data);
    const users = usersData.userslist;
    const existingUser = users.find(user => user.name === name);
    if (existingUser) {
      return res.status(409).json({ message: 'Username already exists' });
    }
    users.push({ name, password });
    fs.writeFile('users.json', JSON.stringify(usersData, null, 2), (err) => {
      if (err) {
        return res.status(500).json({ message: 'Error writing to users.json' });
      }
      res.json({ message: 'User registered successfully' });
    });
  });
});

// 用户登录
app.post('/api/login', (req, res) => {
  const { name, password } = req.body;
  fs.readFile('users.json', (err, data) => {
    if (err) {
      return res.status(500).json({ message: 'Error reading users.json' });
    }
    const usersData = JSON.parse(data);
    const users = usersData.userslist;
    const user = users.find(user => user.name === name && user.password === password);
    if (user) {
      res.json({ message: 'Login successful', username: user.name });
    } else {
      res.status(401).json({ message: 'Invalid username or password' });
    }
  });
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});